<?php
class ImgModel {
	//远程下载图片
	public function down_img($url,$sid='vod',$config){
       $chr = strrchr($url,'.');
	   $imgUrl = uniqid();
	   $imgPath = $sid.'/'.date($config['upload_style'],time()).'/';
	   $imgPath_s = './'.$config['upload_path'].'-s/'.$imgPath;
	   $filename = './'.$config['upload_path'].'/'.$imgPath.$imgUrl.$chr;
	   $get_file = $this->ff_file_get_contents2($url);

	   if ($get_file) {
		   $this->write_file($filename,$get_file);
           include_once 'Image.class.php';
           $cls_img = new Image();

		   if($config['upload_water']){
			   $cls_img::water($filename,$config['upload_water_img'],'',$config['upload_water_pct'],$config['upload_water_pos']);
		   }		   
		   //是否生成缩略图
		   if($config['upload_thumb']){
			   mkdirss($imgPath_s);
               $cls_img::thumb($filename,$imgPath_s.$imgUrl.$chr,'',$config['upload_thumb_w'] ,$config['upload_thumb_h'],true);
		   }

		   return $imgPath.$imgUrl.$chr;
	   }else{
			return $url;
	   } 
	}	


    // 采集内核
   public  function ff_file_get_contents2($url,$timeout=3,$referer=null){
        if(function_exists('curl_init')){
            $ch = curl_init();
            curl_setopt ($ch, CURLOPT_URL, $url);
            curl_setopt ($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
            if($referer){
                curl_setopt ($ch, CURLOPT_REFERER, $referer);
            }
            $content = curl_exec($ch);
            curl_close($ch);
            if($content){
                return $content;
            }
        }
        $ctx = stream_context_create(array('http'=>array('timeout'=>$timeout)));
        $content = @file_get_contents($url, 0, $ctx);
        if($content){
            return $content;
        }
        return false;
    }

    //写入文件
    function write_file($l1, $l2=''){
        $dir = dirname($l1);
        if(!is_dir($dir)){
            $this->mkdirss($dir);
        }
        return @file_put_contents($l1, $l2);
    }


    //递归创建文件
    function mkdirss($dirs,$mode=0777) {
        if(!is_dir($dirs)){
            $this->mkdirss(dirname($dirs), $mode);
            return @mkdir($dirs, $mode);
        }
        return true;
    }
}
?>